package com.example.service;

import cn.hutool.crypto.digest.BCrypt;
import com.example.entity.*;
import com.example.exception.CustomException;
import com.example.mapper.OrganizationMemberMapper;
import com.example.mapper.StudentInfoMapper;
import com.example.mapper.SysUserMapper;
import com.github.pagehelper.PageHelper;
import com.github.pagehelper.PageInfo;
import io.micrometer.common.util.StringUtils;
import jakarta.annotation.Resource;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.BeanUtils;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.time.LocalDateTime;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

/**
 * 管理员业务处理
 **/
@Service
public class SysUserService {

    private static final Logger log = LoggerFactory.getLogger(SysUserService.class);

    @Resource
    private SysUserMapper sysUserMapper;
    @Resource
    private StudentInfoMapper studentInfoMapper;
    @Resource
    private OrganizationMemberMapper organizationMemberMapper;

    /**
     * 新增用户和学生信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void addWithStudentInfo(SysUser sysUser, StudentInfo studentInfo) {
        // 添加用户基本信息
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword(BCrypt.hashpw("123456"));
        }
        sysUserMapper.insert(sysUser);

        // 添加学生信息
        if (studentInfo != null) {
            studentInfo.setUserId(sysUser.getId());
            studentInfoMapper.insert(studentInfo);
        }
    }

    public void addWithMemberInfo(SysUser sysUser, OrganizationMember memberInfo) {
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword(BCrypt.hashpw("123456"));
        }
        sysUserMapper.insert(sysUser);
        if (memberInfo != null) {
            memberInfo.setUserId(sysUser.getId());
            organizationMemberMapper.insert(memberInfo);
        }
    }

    /**
     * 新增用户
     * @param sysUser
     */
    public void add(SysUser sysUser) {
        //密码为空时添加默认密码为123456，需要加密
        if (StringUtils.isBlank(sysUser.getPassword())) {
            sysUser.setPassword(BCrypt.hashpw("123456"));
        }
        sysUserMapper.insert(sysUser);
    }

    /**
     * 更新用户和学生信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void updateWithStudentInfo(SysUser sysUser, StudentInfo studentInfo) {
        // 更新用户基本信息
        sysUserMapper.updateById(sysUser);

        // 更新学生信息
        if (studentInfo != null) {
            studentInfo.setUserId(sysUser.getId());
            StudentInfo existingInfo = studentInfoMapper.selectByUserId(sysUser.getId());
            if (existingInfo != null) {
                studentInfo.setId(existingInfo.getId());
                studentInfoMapper.updateById(studentInfo);
            } else {
                studentInfoMapper.insert(studentInfo);
            }
        }
    }
    @Transactional(rollbackFor = Exception.class)
    public void updateWithMemberInfo(SysUser sysUser, OrganizationMember memberInfo) {
        // 更新用户基本信息
        sysUserMapper.updateById(sysUser);
        if (memberInfo != null) {
            memberInfo.setUserId(sysUser.getId());
            OrganizationMember existingInfo = organizationMemberMapper.getByUserId(sysUser.getId());
            if (existingInfo != null) {
                memberInfo.setId(existingInfo.getId());
                organizationMemberMapper.updateById(memberInfo);
            } else {
                organizationMemberMapper.insert(memberInfo);
            }
        }
    }

    /**
     * 删除用户和关联的学生信息
     */
    @Transactional(rollbackFor = Exception.class)
    public void deleteWithStudentInfo(Integer id) {
        // 先删除学生信息
        studentInfoMapper.deleteByUserId(id);
        // 再删除用户信息
        sysUserMapper.deleteById(id);
    }

    /**
     * 批量删除用户和关联的学生信息
     * @param ids
     */
    @Transactional
    public void deleteBatch(List<Integer> ids) {
        for (Integer id : ids) {
            this.deleteWithStudentInfo(id);
        }
    }

    /**
     * 查询用户信息（包含学生信息）
     */
    public Map<String, Object> selectWithStudentInfo(Long id) {
        Map<String, Object> result = new HashMap<>();

        // 获取用户基本信息
        SysUser sysUser = sysUserMapper.selectById(id);
        result.put("sysUser", sysUser);

        // 如果是学生类型，则获取学生信息
        if (sysUser != null && sysUser.getUserType() == 5) {
            StudentInfo studentInfo = studentInfoMapper.selectByUserId(sysUser.getId());
            result.put("studentInfo", studentInfo);
        }

        return result;
    }
    /**
     * 搜索用户
     */
    public List<SysUser> searchUsers(SysUser query, List<Integer> userTypes) {
        return sysUserMapper.searchUsers(query, userTypes);
    }



    /**
     * 删除
     */
    public void deleteById(Integer id) {
        sysUserMapper.deleteById(id);
    }




    /**
     * 修改
     */
    public void updateById(SysUser sysUser) {
        sysUserMapper.updateById(sysUser);
    }

    /**
     * 根据ID查询
     */
    public SysUser selectById(Long id) {
        return sysUserMapper.selectById(id);
    }

    /**
     * 查询所有
     */
    public List<SysUser> selectAll(SysUser sysUser) {
        return sysUserMapper.selectAll(sysUser);
    }

    /**
     * 分页查询
     */
    public PageInfo<SysUser> selectPage(SysUser sysUser, Integer pageNum, Integer pageSize) {
        PageHelper.startPage(pageNum, pageSize);
        List<SysUser> list = sysUserMapper.selectAll(sysUser);
        return PageInfo.of(list);
    }

    /**
     * 登录
     */
    public SysUser login(LoginDTO loginDTO) {
        // 1. 根据用户名查询用户
        SysUser dbUser = sysUserMapper.selectByUsername(loginDTO.getUsername());
        if (dbUser == null) {
            throw new CustomException("用户名或密码错误");
        }

        // 2. 校验密码
        if (!BCrypt.checkpw(loginDTO.getPassword(), dbUser.getPassword())) {
            throw new CustomException("用户名或密码错误");
        }

        // 3. 判断用户状态
        if (dbUser.getStatus() == 0) {
            throw new CustomException("用户已禁用");
        }

        // 4. 密码赋空值
        dbUser.setPassword("");
        return dbUser;
    }

    /**
     * 修改密码
     */
    // SysUserService.java
    public int updatePassword(PasswordUpdateDTO passwordDTO) {
        // 1. 获取当前登录用户
        SysUser currentUser = sysUserMapper.selectById(passwordDTO.getUserId());
        if (currentUser == null) {
            throw new CustomException("用户不存在");
        }


        // 2. 验证原密码是否正确
        if (!BCrypt.checkpw(passwordDTO.getOldPassword(), currentUser.getPassword())) {
            throw new CustomException("原密码错误");
        }

        // 3. 验证两次密码是否一致
        if (!passwordDTO.getNewPassword().equals(passwordDTO.getConfirmPassword())) {
            throw new CustomException("两次输入的密码不一致");
        }

        // 4. 加密新密码并更新
        SysUser updateUser = new SysUser();
        updateUser.setId(passwordDTO.getUserId());
        updateUser.setPassword(BCrypt.hashpw(passwordDTO.getNewPassword()));
        updateUser.setUpdateTime(LocalDateTime.now().toString());

        return sysUserMapper.updateById(updateUser);
    }


    public void register(SysUser user) {
        // 1. 参数校验
        if (StringUtils.isBlank(user.getUsername())
                || StringUtils.isBlank(user.getPassword())
                || StringUtils.isBlank(user.getRealName())
                || StringUtils.isBlank(user.getPhone())
                || StringUtils.isBlank(user.getEmail())) {
            throw new CustomException("必填信息不能为空");
        }
        // 2. 检查用户名是否已存在
        SysUser existUser = sysUserMapper.selectByUsername(user.getUsername());
        if (existUser != null) {
            throw new CustomException("用户名已存在");
        }

        // 3. 设置默认值
        user.setUserType(5);  // 默认学生
        user.setStatus(1);    // 默认正常状态
        user.setCreateTime(LocalDateTime.now().toString());
        user.setUpdateTime(LocalDateTime.now().toString());

        //密码加密
        user.setPassword(BCrypt.hashpw(user.getPassword()));

        // 5. 保存用户
        try {
            sysUserMapper.insert(user);
        } catch (Exception e) {
            log.error("注册失败", e);
            throw new CustomException("注册失败，请稍后重试");
        }

    }



}